<?php

namespace app\api\controller\pifa;

use app\common\controller\Api;
use think\Config;
use think\Db;
use think\Validate;
use think\Session;
use fast\WechatMini;
use fast\Feiyong;
use addons\third\model\Third;
use think\Log;
use think\Request;
use fast\Http;
use think\Exception;
use addons\third\library\Service;
use app\api\model\Goodsitem;
use addons\epay\library\Service as PayService;
use app\api\library\Order as PayOrder;
use fast\Tongbu;
use addons\litestore\model\Litestorefreight;
use addons\litestore\model\Wxlitestoregoods;

use fast\AdapayUtil;
use fast\Saobei;
use fast\Huipay;

class Orderpay extends Api
{

    protected $noNeedLogin = ['login','getconfig','getMendian1','token','getfenlei'];
    protected $noNeedRight = ['*'];



    public function pay()
    {
        $post = $this->request->request();


        $map['id'] = $post['order_sn'];
        $map['user_id'] = $this->auth->id;
        $map['paystate'] = 0;
        $map['orderstate'] = 0;
        $user = Db::table('fa_user')->find($this->auth->id);
        $order = Db::table('fa_pifa_order')->where($map)->find();

        if (empty($order)) {
            $this->error("订单不存在");
        }
        $data = [];

        if ($order['expiretime'] < time()) {
            $this->error("订单已过期");
        }
 


        switch ($post['payment']) {
            case 'wallet':


                // if ($order['is_score'] == 0) {
                //     if ($user['money'] < $order['price']) {
                //         $this->error('余额不足');
                //     }

                //     $moneyres = \app\common\model\User::money2(-$order['price'], $this->auth->id, '购买商品');
                //     if (empty($moneyres)) {
                //         throw new Exception("账户余额不足");
                           
                //     } 
                // }else{
                //     if ($user['money'] < $order['yunfei']) {
                //         $this->error('余额不足');
                //     }

                //     $moneyres = \app\common\model\User::money2(-$order['yunfei'], $this->auth->id, '积分兑换支付运费');
                //     if (empty($moneyres)) {
                //         throw new Exception("账户余额不足");
                           
                //     } 
                // }

               
                
                // $updata['orderstate'] = 1;
                // $updata['paystate'] = 1;
                // $updata['paytime'] = date('Y-m-d H:i:s');

                // Db::table('fa_pifa_order')->where($map)->update($updata);

              
                // $this->success('下单成功');
            break;


            case 'wechat':
                $paytype = 'wechat';
                $method = 'miniapp';
                $third = Third::where('platform', 'wechat')->where('apptype', 'miniapp')->where('user_id', $this->auth->id)->find();
                
                if (!$third) {
                    $this->error("未找到登录用户信息");
                }
                $openid = $third['openid'];

                $indata2['order_no'] = 'WX'.date("YmdHis"). $this->auth->id. mt_rand(100, 999);
                $indata2['order_id'] = $order['id'];


                if ($order['is_score'] == 0) {
                    $indata2['price'] = $order['price'];
                }else{
                    $order['price'] = $order['yunfei'];
                    $indata2['price'] = $order['price'];
                }
                $indata2['createtime'] = time();
                Db::table('fa_pifa_orderliushui')->insertGetId($indata2);    
                $orderid = $indata2['order_no'];
                $paytype = 'wechat';
                $notifyurl = 'http://dongpingyun.xinanqy.com/api/pay/index';
               
                $ip = request()->ip();

                $config = get_addon_config('third');
                $params = [

                    'appid'      => $config['wechat_mini']['app_id'],

                    'secret'     => $config['wechat_mini']['app_secret'],

                    'js_code'    => $post['code'],

                    'grant_type' => 'authorization_code'

                ];


                $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
                

                if (!$result['ret']) {
                     $this->error("请求支付失败");
                }


                // var_dump($order['price']);
                $result['msg'] = json_decode($result['msg'],true);
             
                try {
                    
                    $res = Huipay::addOrder($result['msg']['session_key'],$indata2['order_no'],$order['price'],$notifyurl,$ip);

                } catch (Exception $e) {

                    $this->error($e->getMessage());

                }

                if (!$res['success']) {
                    $this->error("请求支付失败");
                }
                
                

                   //如果是Collection则需要转换为数组

                $result = json_decode($res['result'],true);
                
                
                if($result['orderStatus'] == 'FAIL'){
                      $this->error("请求支付失败");
                }
                
                
                logs('third_pay',json_encode($result,JSON_UNESCAPED_UNICODE));  

                $qrCode = json_decode($result['qrCode'],true);
                // $qrCode['signData'] = json_decode($qrCode['signData'],true);

                // $qrCode['amount']['currency'] = 'CNY';
                $resdata['pay'] = $qrCode;
                // $resdata['pay'] = json_decode($resdata['pay'],true);

              
               
                $resdata['price'] = floatval($order['price']);
                $resdata['order_no'] = $indata2['order_no'];
                $this->success("请求成功", $resdata);
                return;
            break;
            
         
        }

    }


}